package com.lw.leetcode.str.a;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * str
 * 720. 词典中最长的单词
 *
 * @Author liw
 * @Date 2021/7/10 16:03
 * @Version 1.0
 */
public class LongestWord {

    public static void main(String[] args) {
        LongestWord test = new LongestWord();
//        String[] arr = {"yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y"};
        String[] arr = {"a","banana","app","appl","ap","apply","apple"};
        String s = test.longestWord(arr);
        System.out.println(s);
    }

    public String longestWord(String[] words) {
        Arrays.sort(words, (a, b) -> a.length() == b.length() ? a.compareTo(b) : a.length() - b.length());
        String ans = words[0];
        int l = ans.length();
        if (l != 1) {
            return "";
        }
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            int length = word.length();
            if (length == 1) {
                map.put(word, 1);
            } else if (map.get(word.substring(0, length - 1)) != null) {
                map.put(word, 1);
                if (length > l) {
                    ans = word;
                    l = length;
                }
            }
        }
        return ans;
    }
}
